package com.ciwong.epaper.modules.epaper.ui;

import android.content.Intent;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.adapter.ListenSpeakChooseWorkAdapter;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakChildren;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakExAminAtion;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakExaminBean;
import com.ciwong.epaper.modules.epaper.bean.ListenSpeakParts;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.List;

/**
 * @description:听说模考选择大题页面
 * @author: wyk
 * @time: 2021/5/20 10:34
 */
public class ListenSpeakChooseWorkActivity extends BaseActivity {


    //返回按钮
    private ImageView choose_work_go_back;
    //全选按钮
    private CheckBox listen_speak_choose_work;

    private ListView listen_speak_work_list_view;

    private TextView listen_speak_choose_detail_text;

    private String versionId;

    private String resourceUrl;

    private String resourceName;

    private ListenSpeakChooseWorkAdapter listenSpeakChooseWorkAdapter;

    private ListenSpeakExaminBean listenSpeakExaminBean = new ListenSpeakExaminBean();
    //听说模考作业详情
    private ListenSpeakExAminAtion listenSpeakExAminAtion = new ListenSpeakExAminAtion();

    private String tag;

    //作业分数
    private float workScore;

    //大题数量
    private int examinCount;
    //总作业时长
    private double workLong;
    //选中的作业时长
    private double chooseListenSpeakWorkLong;

    private TextView listen_speak_work_long_text;

    private RelativeLayout choose_sentence_finish;

    @Override
    protected int setView() {
        return R.layout.activity_listen_speak_choose_work;
    }

    @Override
    protected void findViews() {
        choose_work_go_back = findViewById(R.id.choose_work_go_back);
        listen_speak_choose_work =  findViewById(R.id.listen_speak_choose_work);
        listen_speak_work_list_view = findViewById(R.id.listen_speak_work_list_view);
        listen_speak_choose_detail_text = findViewById(R.id.listen_speak_choose_detail_text);
        choose_sentence_finish =  findViewById(R.id.choose_sentence_finish);
        listen_speak_work_long_text = findViewById(R.id.listen_speak_work_long_text);

        listen_speak_choose_work.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                if (b){
                    listen_speak_choose_work.setChecked(true);
                    listen_speak_choose_work.setSelected(true);
                    listenSpeakExaminBean.setCheckCount(examinCount);
                    List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
                    for (int i = 0; i < parts.size(); i++) {
                        parts.get(i).setChecked(true);
                    }
                    listenSpeakChooseWorkAdapter.notifyDataSetChanged();
                }else {
                    listen_speak_choose_work.setChecked(false);
                    listen_speak_choose_work.setSelected(true);
                    listenSpeakExaminBean.setCheckCount(0);
                    List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
                    for (int i = 0; i < parts.size(); i++) {
                        parts.get(i).setChecked(false);
                    }
                    listenSpeakChooseWorkAdapter.notifyDataSetChanged();
                }
            }
        });

        choose_sentence_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        choose_work_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void init() {
        hideTitleBar();
        Intent intent = getIntent();
        versionId = intent.getStringExtra(IntentFlag.INTENT_FLAG_VERSION_ID);
        resourceName = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME);
        resourceUrl = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL);
        tag = intent.getStringExtra(IntentFlag.INTENT_FLAG_TAG);
        workLong = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_LONG,0);
        listenSpeakExaminBean = (ListenSpeakExaminBean) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        if (null != listenSpeakExaminBean) {
            listenSpeakChooseWorkAdapter = new ListenSpeakChooseWorkAdapter(listenSpeakExaminBean, ListenSpeakChooseWorkActivity.this, versionId, tag);
            listen_speak_work_list_view.setAdapter(listenSpeakChooseWorkAdapter);
        }
    }

    /**
     * 设置选中作业详情
     */
    public void setCheckStatus() {
        chooseListenSpeakWorkLong = workLong/examinCount*listenSpeakExaminBean.getCheckCount();
        chooseListenSpeakWorkLong = Math.ceil(chooseListenSpeakWorkLong);

        SpannableStringBuilder chooseCountText = new SpannableStringBuilder("已选择 "+listenSpeakExaminBean.getCheckCount()+" 个大题");
        SpannableStringBuilder chooseWorkLongText = new SpannableStringBuilder("预计 "+(int)chooseListenSpeakWorkLong+" 分钟");
        ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#5ce191"));

        if (listenSpeakExaminBean.getCheckCount() < 10){
            chooseCountText.setSpan(GreenSpan, 4, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }else {
            chooseCountText.setSpan(GreenSpan, 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (chooseListenSpeakWorkLong>=100){
            chooseWorkLongText.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }else if (chooseListenSpeakWorkLong < 10){
            chooseWorkLongText.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }else {
            chooseWorkLongText.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        listen_speak_choose_detail_text.setText(chooseCountText);
        listen_speak_work_long_text.setText(chooseWorkLongText);
        if (examinCount == listenSpeakExaminBean.getCheckCount()){
            listen_speak_choose_work.setChecked(true);
            listen_speak_choose_work.setSelected(true);
        }else if (0 == listenSpeakExaminBean.getCheckCount()){
            listen_speak_choose_work.setChecked(false);
            listen_speak_choose_work.setSelected(true);
        }else {
            listen_speak_choose_work.setChecked(true);
            listen_speak_choose_work.setSelected(false);
        }
        listenSpeakChooseWorkAdapter.notifyDataSetChanged();
    }

    @Override
    protected void loadData() {
        if (tag.equals(RequestCode.TeaWorkContent.LISTEN_SPRAK)){
            if (null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion() && 0 != listenSpeakExaminBean.getCheckCount()){
                examinCount = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts().size();
                workLong = workLong/listenSpeakExaminBean.getCheckCount()*examinCount;
                setCheckStatus();
                listenSpeakChooseWorkAdapter.notifyDataSetChanged();
            }else {
                showCricleProgress();
                ListenSpeakExaminAtion();
            }

        }else if (tag.equals(RequestCode.TeaWorkContent.ANSWER_ONLINE)){
            if (null != listenSpeakExaminBean && null != listenSpeakExaminBean.getListenSpeakExAminAtion() && 0 != listenSpeakExaminBean.getCheckCount()){
                examinCount = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts().size();
                workLong = workLong/listenSpeakExaminBean.getCheckCount()*examinCount;
                setCheckStatus();
                listenSpeakChooseWorkAdapter.notifyDataSetChanged();
            }else {
                showCricleProgress();
                examinationData();
            }

        }else {
            hideCricleProgress();
            ToastUtil.INSTANCE.toastCenterError("加载失败，请稍后重试");
        }
    }

    /**
     * 获取听说模考内容
     */
    private void ListenSpeakExaminAtion() {
        EpaperDao.getInstance().ListenSpeakExaminAtion(versionId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    listenSpeakExAminAtion = (ListenSpeakExAminAtion) data;
                    examinCount = listenSpeakExAminAtion.getParts().size();
                    listenSpeakExaminBean = new ListenSpeakExaminBean();
                    listenSpeakExaminBean.setListenSpeakExAminAtion(listenSpeakExAminAtion);
                    listenSpeakExaminBean.setCheckCount(examinCount);

                    listenSpeakChooseWorkAdapter = new ListenSpeakChooseWorkAdapter(listenSpeakExaminBean, ListenSpeakChooseWorkActivity.this, versionId, tag);
                    listen_speak_work_list_view.setAdapter(listenSpeakChooseWorkAdapter);
                    setCheckStatus();
                    //listenSpeakChooseWorkAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 获取在线作答内容
     */
    public void examinationData(){
        EpaperDao.getInstance().examinationData(versionId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    listenSpeakExAminAtion = (ListenSpeakExAminAtion) data;
                    examinCount = listenSpeakExAminAtion.getParts().size();
                    listenSpeakExaminBean = new ListenSpeakExaminBean();
                    listenSpeakExaminBean.setListenSpeakExAminAtion(listenSpeakExAminAtion);
                    listenSpeakExaminBean.setCheckCount(examinCount);
                    listenSpeakChooseWorkAdapter = new ListenSpeakChooseWorkAdapter(listenSpeakExaminBean, ListenSpeakChooseWorkActivity.this, versionId, tag);
                    listen_speak_work_list_view.setAdapter(listenSpeakChooseWorkAdapter);
                    setCheckStatus();
                }
            }
        });
    }
    @Override
    public void finish() {
        setChooseWork();
        super.finish();
    }


/*    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            setChooseWork();
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }*/

    /**
     * 设置选中的作业 返回
     */
    public void setChooseWork(){
        StringBuffer str = new StringBuffer();
        workScore = 0;
        List<ListenSpeakParts> parts = listenSpeakExaminBean.getListenSpeakExAminAtion().getParts();
        int checkCount = listenSpeakExaminBean.getCheckCount();
        for (int i = 0; i < parts.size(); i++) {
            if (parts.size() == checkCount){
                if (null != parts.get(i).getChildren() && parts.get(i).getChildren().size() > 0){
                    List<ListenSpeakChildren> children = parts.get(i).getChildren();
                    for (int i1 = 0; i1 < children.size(); i1++) {
                        if (null != children.get(i1).getChildren() && children.get(i1).getChildren().size() > 0 ){
                            List<ListenSpeakChildren> childrens = children.get(i1).getChildren();
                            for (int i2 = 0; i2 < childrens.size(); i2++) {
                                workScore = workScore + childrens.get(i2).getQuestion_ref_sorce();
                            }
                        }else {
                            workScore = workScore + children.get(i1).getQuestion_ref_sorce();
                        }
                    }
                }else {
                    workScore = workScore + parts.get(i).getQuestion_ref_sorce();
                }
                if (str.length()==0 || "".equals(str)){
                    str.append(i);
                }else {
                    str.append(","+i);
                }
            }else {
                if (null != parts.get(i).getChildren() && parts.get(i).getChildren().size() > 0) {
                    if (null == parts.get(i).getChecked() || parts.get(i).getChecked()) {
                        List<ListenSpeakChildren> children = parts.get(i).getChildren();
                        for (int i1 = 0; i1 < children.size(); i1++) {
                            if (null != children.get(i1).getChildren() && children.get(i1).getChildren().size() > 0) {
                                List<ListenSpeakChildren> childrens = children.get(i1).getChildren();
                                for (int i2 = 0; i2 < childrens.size(); i2++) {
                                    workScore = workScore + childrens.get(i2).getQuestion_ref_sorce();
                                }
                            } else {
                                workScore = workScore + children.get(i1).getQuestion_ref_sorce();
                            }
                        }
                    }
                }
                if (null == parts.get(i).getChecked() || parts.get(i).getChecked()){
                    if (str.length()==0 || "".equals(str)){
                        str.append(i);
                    }else {
                        str.append(","+i);
                    }
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        /*//作业要求
        jsonObject.put("readtimes",readTime);
        if (readStyle.equals("跟读")){
            jsonObject.put("speekingtype",1);
        }else if (readStyle.equals("朗读")){
            jsonObject.put("speekingtype",2);
        }*/
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_WORD_DETAILS,str.toString());
        intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL,resourceUrl);
        intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME,resourceName);
        intent.putExtra(IntentFlag.INTENT_FLAG_VERSION_ID,versionId);
        intent.putExtra(IntentFlag.INTENT_FLAG_JSONOBJECT,jsonObject.toString());
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_LONG,(int)chooseListenSpeakWorkLong);
        intent.putExtra(IntentFlag.INTENT_FLAG_OBJ,listenSpeakExaminBean);
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_SCORE,workScore);
        setResult(RESULT_OK,intent);

    }
}
